package com.libl.shiro;

import com.libl.pojo.DtsAdmin;
import com.libl.service.DtsAdminService;
import com.libl.service.DtsPermissionService;
import com.libl.service.DtsRoleService;
import com.libl.util.bcrypt.BCryptPasswordEncoder;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    /**
     *授权的方法
     * 1. 获取登录成功的用户信息
     * 2. 查询角色字符串列表和权限字符串列表
     * 3. 封装对象并返回
     * @param principalCollection 当前用户信息收集器
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //从session中获取登录成功的用户信息
        DtsAdmin admin = (DtsAdmin) principalCollection.getPrimaryPrincipal();
        //得到该管理员对应的角色id
        Integer[] roleIds = admin.getRoleIds();

        //查询角色字符串列表
        Set<String> roles = roleService.findRolesByRoleIds(roleIds);
        //查询权限字符串列表
        Set<String> perms = permissionService.findPermsByRoleIds(roleIds);

        //创建返回对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    /**
     * 认证步骤：
     * 1. 获取用户名和密码
     * 2. 根据用户名从数据库中查询用户对象
     * 3. 校验用户信息，有问题就会抛出异常
     * @param authenticationToken 令牌信息，储存了前端传入的用户名和密码
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名和密码
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[])authenticationToken.getCredentials());
        //根据用户名从数据库中查询用户对象
        DtsAdmin admin = adminService.findByUsername(username);
        //校验用户信息，有问题就会抛出异常
        if(admin == null) {
            throw new UnknownAccountException("未知的用户");
        }
        if(admin.getDeleted()) {
            throw new LockedAccountException("账户已锁定");
        }
        // 使用bcrypt加密 数据库密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if(StringUtils.isEmpty(password) || !passwordEncoder.matches(password, admin.getPassword())) {
            throw new CredentialsException("密码错误");
        }

        //密码：在返回后，框架中还会对密码进行校验
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin, password, username);

        return authenticationInfo;
    }

}
